from django.http import JsonResponse
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .serializers import *
from .models import *
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
# res-jwt验证原理
# class LoginViewSet(APIView):
#     '''
#     用户登录
#     '''
#     def post(self, request, *args, **kwargs):
#         user = request.data.get('username')
#         pwd = request.data.get('password')
#
#         # values()得到的是一个字典形式的查询集(QuerySet), 查询集是一个可迭代对象
#         user_object = MallUser.objects.values().filter(login_name=user, user_pwd=pwd).first()
#         if not user_object:
#             return Response({'status': 500, 'message': '服务器发生错误'})
#
#
# class OrderViewSet(APIView):
#     def post(self, request, *args, **kwargs):
#         # 获取token并判断token的合法性
#         token = request.query_params.get('token')
#         print(token)
#         # 一般在认证成功后，把jwt生成的token返回给用户，以后用户再次访问时候需要携带token，此时jwt需要对token进行超时及合法性校验
#         # 1.切割
#         # 2.解密
#         # 3.验证第三段合法性
#         import jwt
#         from jwt import exceptions
#         SALT = 'asdfggdjksalfdiuaohjfiuew354'
#         payload = None
#         msg = None
#         try:
#             # 从token中获取payload【不校验合法性】
#             # unverified_payload = jwt.decode(token, None, False)
#             # print(unverified_payload)
#             # 从token中获取payload【校验合法性】
#             payload = jwt.decode(token, SALT, True)
#             return payload
#         except exceptions.ExpiredSignatureError:
#             msg = 'token已失效'
#         except jwt.DecodeError:
#             msg = 'token认证失败'
#         except jwt.InvalidTokenError:
#             msg ='非法的token'
#         if not payload:
#             return Response({'code': 500, 'message': msg})
#         else:
#             print(payload['user_id'], payload['username'])
#             return Response('订单')

from books.extensions.auth import JwtQueryParamsAuthentication
from books.utils.jwt_auth import createToken
class LoginViewSet(APIView):
    '''
    用户登录
    '''
    authentication_classes = []
    def post(self, request, *args, **kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')

        # values()得到的是一个字典形式的查询集(QuerySet), 查询集是一个可迭代对象
        user_object = MallUser.objects.values().filter(login_name=user, user_pwd=pwd).first()
        # user_object1 = MallUser.objects.values().filter(user_id=user, user_pwd=pwd).first()
        if not user_object:
            return JsonResponse({'code': 500, 'data': '用户名或密码错误'})
        token = createToken({'id': user_object['user_id'], 'username': user_object['login_name']})
        info = {'username': user, 'userId': user_object['user_id'], 'token': token}
        return JsonResponse({'code': 200, 'data': info})


class OrderViewSet(APIView):
    # authentication_classes = [JwtQueryParamsAuthentication, ]
    def post(self, request, *args, **kwargs):
        # print(request.user)
        return Response('订单列表')

class BookViewSet(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BannerViewSet(ModelViewSet):
    authentication_classes = []
    queryset = Banner.objects.all()
    serializer_class = BannerSerializer
    # methods指定允许哪些http请求访问当前视图方法
    # detail指定生成的路由地址中是否要夹带pk值，True为需要
    # @action(methods=['GET'], detail=False, url_path="books/banner/")
    # def findBanners(self, request):
    #     queryset = Banner.objects.values().filter(is_deleted=0)
    #     if (queryset != ''):
    #         # JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
    #         # 它的默认Content - Type头部设置为application / json。它的第一个参数data，应该为一个dict实例。如果safe参数设置为False，它可以是任何可JSON序列化的对象。
    #         return JsonResponse({'status': 200, 'data': list(queryset)}, safe=False)
    #     else:
    #         return JsonResponse({'status': 500, 'data': '服务器发生错误'})


class MallUserViewSet(ModelViewSet):
    authentication_classes = []
    queryset = MallUser.objects.all()
    serializer_class = MallUserSerializer

class UserAddressViewSet(ModelViewSet):
    queryset = UserAddress.objects.all()
    serializer_class = UserAddressSerializer


class GoodsInfoViewSet(ModelViewSet):
    authentication_classes = []
    serializer_class = GoodsInfoSerializer
    queryset = GoodsInfo.objects.all()
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['goods_name', 'goods_intro']
    ordering_fields = ['selling_price']



class GoodsCategoryViewSet(ModelViewSet):
    authentication_classes = []
    serializer_class = GoodsCategorySerializer
    queryset = GoodsCategory.objects.all()

class ShoppingCartViewSet(ModelViewSet):
    serializer_class = ShoppingCartSerializer
    queryset = ShoppingCart.objects.all()


class MallOrderViewSet(ModelViewSet):
    queryset = MallOrder.objects.all()
    filter_backends = [filters.SearchFilter]
    search_fields = ['order_nu',]
    serializer_class = MallOrderSerializer



class OrderItemViewSet(ModelViewSet):
    queryset = OrderItem.objects.all()
    filter_backends = [filters.SearchFilter]
    search_fields = ['goods_name', ]
    serializer_class = OrderItemSerializer


class OrderAddressViewSet(ModelViewSet):
    queryset = OrderAddress.objects.all()
    serializer_class = OrderAddressSerializer
    # def create(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data)
    #     try:
    #         serializer.is_valid(raise_exception=True)
    #     except Exception as e:
    #         print(e)
    #     self.perform_create(serializer)
    #     headers = self.get_success_headers(serializer.data)
    #     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class MallCommentViewSet(ModelViewSet):
    queryset = MallComment.objects.all()
    serializer_class = MallCommentSerializer
    # @action(methods=['GET'], detail=False, url_path="books/mallcomment/")
    # def findMallComment(self, request):
    #     queryset = MallComment.objects.values().all()
    #     if (queryset != ''):
    #         return JsonResponse({'status': 200, 'data': list(queryset)}, safe=False)
    #     else:
    #         return JsonResponse({'status': 500, 'data': '服务器发生错误'})

class GridImgViewSet(ModelViewSet):
    authentication_classes = []
    queryset = GridImg.objects.all()
    serializer_class = GridImgSerializer
    # @action(methods=['GET'], detail=False, url_path="books/gridimg/")
    # def findGridImg(self, request):
    #     queryset = GridImg.objects.values().all()
    #     if (queryset != ''):
    #         return JsonResponse({'status': 200, 'data': list(queryset)}, safe=False)
    #     else:
    #         return JsonResponse({'status': 500, 'data': '服务器发生错误'})